package com.bluerox.updating;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/** 
* 发送http请求类<br><br>
* 
* @author 李建波 
*/
public class HttpService {
	
	private static int BUFFER_SIZE = 4096;
    
	/**
	 * 发送请求，下载文件<br><br>
	 * Example:<br><br>
	 * String baseUrl = "http://loacalhost:8080/race_test/race1.0.0/";<br>
	 * String path = "/home/lijianbo/test/race/temp/status/";<br>
	 * String fileName = "Race_1_0_0_status.xml.zip";<br>
	 * HttpService service = new HttpService();<br>
	 * service.send(baseUrl, path, fileName);<br>
	 * 
	 * @param baseUrl 下载文件的基础URL
	 * @param path 本地存储文件的路径
	 * @param fileName 目标文件名
	 */
	public void send(String baseUrl, String path, String fileName){
		
		FileOutputStream fos = null;
	    BufferedInputStream bis = null;
	    HttpURLConnection httpConnection = null;
	    URL url = null;
	    byte[] buf = new byte[BUFFER_SIZE];
	    int size = 0;
	    
		try {
			url = new URL(baseUrl + fileName);
			
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.connect();
			
			bis = new BufferedInputStream(httpConnection.getInputStream());
			fos = new FileOutputStream(path + File.separator + fileName);
			
			while ((size = bis.read(buf)) != -1){
	            fos.write(buf, 0, size);
			}
			
	        fos.close();
	        bis.close();
	        httpConnection.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
